package com.github.wujichen158.andemusic.newcommands;

import com.github.wujichen158.andemusic.playernbt.MusicTypeProvider;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;

public class GetMusicCommand extends CommandsRoot {
    @Override
    public String getName() {
        return "getmusic";
    }

    @Override
    public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws WrongUsageException {
        if (args.length == 1) {
            getMusic(args[0], sender, server);
        } else if (args.length == 0) {
            getMusic(sender.getName(), sender, server);
        } else {
            send(sender, TextFormatting.YELLOW, "commands.get.usage");
        }
    }

    @Override
    public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos pos) {
        if (args.length == 1) {
            String[] names = server.getOnlinePlayerNames();
            return CommandBase.getListOfStringsMatchingLastWord(args, names);
        }
        return null;
    }

    public void getMusic(String name, ICommandSender sender, MinecraftServer server) throws WrongUsageException {
        try {
            EntityPlayerMP player = getPlayer(server, sender, name);
            Optional.ofNullable(MusicTypeProvider.get(player)).ifPresent(nbt -> {
                send(sender, TextFormatting.AQUA, "commands.get.success", player.getDisplayName(),
                        nbt.getMusicType(), nbt.getMinDelayTime(), nbt.getMaxDelayTime());
            });
        } catch (Exception e) {
            throw new WrongUsageException("commands.get.usage");
        }
    }
}